package day230518;

/**
 * @author 兴趣使然黄小黄
 * @version 1.0
 * @date 2023/5/18 20:11
 * 数组中出现次数超过一半的单词
 */
public class Solution {

    public int MoreThanHalfNum_Solution (int[] numbers) {
        // 众数思想
        int res = numbers[0]; // 假设第一个为众数
        int count = 1; // 统计出现的次数
        for (int i = 1; i < numbers.length; i++) {
            if (numbers[i] == res) {
                ++count;
            } else {
                --count;
            }
            if (count == 0) {
                // 更新众数
                res = numbers[i];
                count = 1;
            }
        }
        count = 0;
        for (int i = 0; i < numbers.length; i++) {
            if (numbers[i] == res) {
                count++;
            }
        }
        return count > numbers.length / 2 ? res : -1;
    }
}
